# 1. add lib path: File-> setting -> project interpreter -> more
# 2. raw_input(): str  input():  type " "
# 3. cv.startWindowThread()

import getpass
import time
import cv2 as cv
import matplotlib.pyplot as plot
import thread
import threading



class Th1 (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    def run(self):
        while True:
            ret, img = cap.read()
            Img = cv.resize(img, (480, 320), interpolation=cv.INTER_CUBIC)
            cv.imshow("show", Img)
        print "run"
        print "Starting " + self.name
        threadLock.acquire()
        pass
        threadLock.release()



def savePic():
    count = 0
    if raw_input("create new txt, yes or no: ") == 'yes':
        File_time = time.strftime('%m-%d-%H-%M-%S', time.localtime(time.time()))
        File_host = getpass.getuser()
        File_name = File_host + '-' + File_time + '.txt'
        pic_name_base = File_host + '-' + File_time + '-'
    else:
        File_name = raw_input("plz input txt file name without .txt: ")
        pic_name_base = File_name + '-'
        File_name += '.txt'
        fl = open(File_name, 'rb')
        while True:
            buffer = fl.read(8192 * 1024)
            if not buffer:
                break
            count += buffer.count('\n')
        fl.close()

    print File_name
    print 'count:', count
    fo = open(File_name, "a+")  # create a new file

    while True:
        raw = raw_input("raw_input: ")
        print raw
        if raw == 'a':
            fo.write(pic_name_base + str(count) + '.jpg' + '   a' + "\n");  # write lines
        elif raw == 'b':
            fo.write(pic_name_base + str(count) + '.jpg' + '   b' + "\n");  # write lines
        else:
            break
        count += 1

    fo.close()
    fo = open(File_name, "r")
    str = fo.read()
    print 'output:\n', str

threadLock = threading.Lock()
threads = []
cap = cv.VideoCapture(0)


if __name__ == '__main__':
    w1 = cv.namedWindow("w1",cv.WINDOW_NORMAL)
    w2 = cv.namedWindow("w2",cv.WINDOW_NORMAL)
    cv.startWindowThread()
    thread_cap = Th1(1,"th1",1)
    thread_cap.start()
    threads.append(thread_cap)
    cv.waitKey()
    savePic()
    cv.destroyAllWindows()
    # for t in threads:
    #     t.join()
    print "Exiting Main Thread"

